/**
 * API服务 - 处理与后端的所有API调用
 */

// API基础URL
const API_BASE_URL = 'http://localhost:8080/api';

/**
 * 通用API请求函数
 * @param {string} endpoint - API端点
 * @param {string} method - HTTP方法 (GET, POST, PUT, DELETE)
 * @param {Object} data - 请求数据 (可选)
 * @returns {Promise} - 返回Promise对象
 */
async function apiRequest(endpoint, method = 'GET', data = null) {
    const url = `${API_BASE_URL}${endpoint}`;

    const options = {
        method,
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        },
        credentials: 'include' // 包含cookies
    };

    if (data) {
        options.body = JSON.stringify(data);
    }

    try {
        const response = await fetch(url, options);

        // 检查响应状态
        if (!response.ok) {
            const errorData = await response.json().catch(() => ({}));
            throw new Error(errorData.message || `请求失败: ${response.status}`);
        }

        // 检查是否有响应内容
        const contentType = response.headers.get('content-type');
        if (contentType && contentType.includes('application/json')) {
            return await response.json();
        }

        return {};
    } catch (error) {
        console.error('API请求错误:', error);
        throw error;
    }
}

/**
 * 用户相关API
 */
const userApi = {
    // 用户注册
    register: (userData) => apiRequest('/users/register', 'POST', userData),

    // 用户登录
    login: (credentials) => apiRequest('/users/login', 'POST', credentials),

    // 获取用户信息
    getUserInfo: (userId) => apiRequest(`/users/${userId}`),

    // 更新用户信息
    updateUserInfo: (userId, userData) => apiRequest(`/users/${userId}`, 'PUT', userData)
};

/**
 * 健康档案相关API
 */
const healthProfileApi = {
    // 获取用户健康档案
    getHealthProfile: (userId) => apiRequest(`/users/${userId}/health-profile`),

    // 创建或更新健康档案
    saveHealthProfile: (userId, profileData) => apiRequest(`/users/${userId}/health-profile`, 'POST', profileData),

    // 计算BMI
    calculateBMI: (userId) => apiRequest(`/users/${userId}/bmi`),

    // 计算基础代谢率
    calculateBMR: (userId) => apiRequest(`/users/${userId}/bmr`),

    // 获取营养需求
    getNutritionNeeds: (userId) => apiRequest(`/users/${userId}/nutrition-needs`),
    
    // 获取健康建议
    getHealthRecommendations: (userId) => apiRequest(`/users/${userId}/health-profile/health-recommendations`),
    
    // 获取AI健康建议（SSE流式响应）
    getAIHealthAdvice: (userId, callbacks) => {
        const url = `${API_BASE_URL}/users/${userId}/health-profile/ai-health-advice`;
        const eventSource = new EventSource(url);
        
        // 处理消息事件
        eventSource.addEventListener('message', (event) => {
            if (callbacks.onMessage) {
                callbacks.onMessage(event.data);
            }
        });
        
        // 处理错误事件
        eventSource.addEventListener('error', (event) => {
            if (callbacks.onError) {
                callbacks.onError(event);
            }
            eventSource.close();
        });
        
        // 返回EventSource实例，以便调用者可以在适当的时候关闭连接
        return eventSource;
    }
};

/**
 * 食品分析相关API
 */
const foodAnalysisApi = {
    // 获取所有食品
    getAllFoods: () => apiRequest('/food-items'),

    // 获取食品详情
    getFoodDetails: (foodId) => apiRequest(`/food-items/${foodId}`),

    // 上传食品图片进行分析
    analyzeFood: (formData) => {
        const url = `${API_BASE_URL}/food-items/analyze-image`;
        return fetch(url, {
            method: 'POST',
            body: formData,
            credentials: 'include'
        }).then(response => {
            if (!response.ok) {
                throw new Error(`请求失败: ${response.status}`);
            }
            return response.json();
        });
    },

    // 搜索食品
    searchFoods: (query) => apiRequest(`/food-items/search?q=${encodeURIComponent(query)}`),
    
    // 获取食品健康建议（SSE流式响应）
    getFoodHealthAdvice: (userId, foodData, callbacks) => {
        // 构建完整的提示词，包含用户健康档案信息、食品分析结果和食用建议提示词
        const customPrompt = `你是一个精通营养学、医术高明的专家，我会给你一个病人的基础信息，以及一个食品的分析结果，给我输出适合这个病人的食用建议，需要符合病人的身体情况，如果不建议食用也说出具体的理由，总共 300 字左右。`;

        // 构建URL参数
        const params = new URLSearchParams();
        params.append('overridePrompt', customPrompt);
        
        // 添加食品数据作为查询参数
        if (foodData) {
            Object.entries(foodData).forEach(([key, value]) => {
                if (value !== null && value !== undefined) {
                    params.append(`foodData[${key}]`, value);
                }
            });
        }
        
        // 使用健康档案的AI建议接口，传递提示词和食品数据
        const url = `${API_BASE_URL}/users/${userId}/health-profile/ai-health-advice?${params.toString()}`;
        const eventSource = new EventSource(url);
        
        // 处理消息事件
        eventSource.addEventListener('message', (event) => {
            if (callbacks.onMessage) {
                callbacks.onMessage(event.data);
            }
        });
        
        // 处理错误事件
        eventSource.addEventListener('error', (event) => {
            if (callbacks.onError) {
                callbacks.onError(event);
            }
            eventSource.close();
        });
        
        // 返回EventSource实例，以便调用者可以在适当的时候关闭连接
        return eventSource;
    }
};

/**
 * 饮食记录相关API
 */
const dietRecordApi = {
    // 获取用户的饮食记录
    getUserDietRecords: (userId) => apiRequest(`/users/${userId}/diet-records`),

    // 添加饮食记录
    addDietRecord: (userId, recordData) => apiRequest(`/users/${userId}/diet-records`, 'POST', recordData),

    // 更新饮食记录
    updateDietRecord: (userId, recordId, recordData) => apiRequest(`/users/${userId}/diet-records/${recordId}`, 'PUT', recordData),

    // 删除饮食记录
    deleteDietRecord: (recordId) => apiRequest(`/users/${userId}/diet-records/${recordId}`, 'DELETE'),
    
    // 获取指定日期各餐食类型的营养摄入统计
    getMealNutritionStats: (userId, date) => apiRequest(`/users/${userId}/diet-records/meal-nutrition?date=${date}`),
    
    // 比较用户的实际营养摄入与推荐摄入
    compareActualVsRecommendedIntake: (userId, date) => apiRequest(`/users/${userId}/diet-records/compare-intake?date=${date}`),
    
    // 获取用户在指定日期范围内的营养趋势数据
    getNutritionTrend: (userId, startDate, endDate) =>
        apiRequest(`/users/${userId}/diet-records/nutrition-trend?startDate=${startDate}&endDate=${endDate}`),
        
    // 获取用户在指定日期的营养素占比数据
    getNutritionRatio: (userId, date, period = 'daily') =>
        apiRequest(`/users/${userId}/diet-records/nutrition-ratio?date=${date}&period=${period}`),
        
    // 获取用户在指定日期的热量摄入目标完成情况
    getCalorieGoalCompletion: (userId, date) =>
        apiRequest(`/users/${userId}/diet-records/calorie-goal?date=${date}`),
        
    // 获取用户在指定周期内的营养素摄入与推荐值对比数据
    getNutritionComparison: (userId, date, period = 'weekly') =>
        apiRequest(`/users/${userId}/diet-records/nutrition-comparison?date=${date}&period=${period}`),
    
    // 获取用户在指定周期内的食物类型摄入分布数据
    getFoodCategoryDistribution: (userId, period, date) =>
        apiRequest(`/users/${userId}/diet-records/food-category-distribution?date=${date}&period=${period}`),
    
    // 获取用户在指定日期范围内的BMI趋势数据
    getBMITrend: (userId, startDate, endDate) =>
        apiRequest(`/users/${userId}/diet-records/bmi-trend?startDate=${startDate}&endDate=${endDate}`),
    
    // 通过食品名称添加食品到饮食记录
    addFoodItemByName: (userId, dietRecordId, foodData) =>
        apiRequest(`/users/${userId}/diet-records/${dietRecordId}/food-items`, 'POST', foodData),
        
    // 创建饮食记录并同时添加多个食品（一次性计算营养信息）
    createDietRecordWithFoodItems: (userId, dietRecordData, foodItems) =>
        apiRequest(`/users/${userId}/diet-records/with-food-items`, 'POST', {
            dietRecord: dietRecordData,
            foodItems: foodItems
        })
};

// 导出API服务
window.apiService = {
    user: userApi,
    healthProfile: healthProfileApi,
    foodAnalysis: foodAnalysisApi,
    dietRecord: dietRecordApi
};